package club.cearnach.api.service.impl;


import club.cearnach.api.dao.IUserFavoriteDao;
import club.cearnach.entity.UserMovieId;
import club.cearnach.entity.UserFavorite;
import club.cearnach.api.exception.UserFavoriteException;
import club.cearnach.api.form.PageBean;
import club.cearnach.api.service.IUserFavoriteService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 阮胜
 * @date 2018/5/16 11:13
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserFavoriteServiceImpl implements IUserFavoriteService {
    private final IUserFavoriteDao userFavoriteDao;

    public UserFavoriteServiceImpl(IUserFavoriteDao userFavoriteDao) {
        this.userFavoriteDao = userFavoriteDao;
    }

    @Override
    public Page<UserFavorite> findAll(Pageable pageable) {
        return userFavoriteDao.findAll(pageable);
    }

    @Override
    public UserFavorite save(UserFavorite userFavorite) {
        return userFavoriteDao.save(userFavorite);
    }

    @Override
    public void delete(UserMovieId id) throws UserFavoriteException {
        userFavoriteDao.findById(id).orElseThrow(() -> new UserFavoriteException(UserFavoriteException.USER_RATE_CAN_NOT_FOUNT));
        userFavoriteDao.deleteById(id);
    }

    @Override
    public Page<UserFavorite> findAllOrderByCreateDate(PageBean pageBean) {
        return userFavoriteDao.findAll(PageRequest.of(pageBean.getPage(), pageBean.getSize(), Sort.by(Sort.Direction.DESC, "createDate")));
    }

    @Override
    public Page<UserFavorite> findByMovieId(Integer movieId, PageBean pageBean) {
        return userFavoriteDao.findByUserMovieIdMovieId(movieId, PageRequest.of(pageBean.getPage(), pageBean.getSize(), Sort.by(Sort.Direction.DESC, "createDate")));
    }

    @Override
    public Page<UserFavorite> findByUserId(Integer userId, PageBean pageBean) {
        return userFavoriteDao.findByUserMovieIdUserId(userId, PageRequest.of(pageBean.getPage(), pageBean.getSize(), Sort.by(Sort.Direction.DESC, "createDate")));
    }

    @Override
    public UserFavorite findByUserIdAndMovieId(Integer userId, Integer movieId) throws UserFavoriteException {
        return userFavoriteDao.findByUserMovieIdUserIdAndUserMovieIdMovieId(userId, movieId).orElseThrow(() -> new UserFavoriteException(UserFavoriteException.USER_RATE_CAN_NOT_FOUNT));
    }

    @Override
    public void deleteIn(UserMovieId[] idArr) {
        for (UserMovieId id : idArr) {
            try {
                delete(id);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public long count() {
        return userFavoriteDao.count();
    }


}